import { login, getUserInfo, getUserDetailById } from "@/api/user"
import { getToken, setToken, removeToken } from "@/utils/auth"
import { resetRouter } from '@/router'

const state = {
  token: getToken() || '',
  userInfo: {}
}
const mutations = {
  setToken(state, data) {
    state.token = data
    setToken(data)
  }, removeToken(state) {
    state.token = ''
    // 同时清理持久化数据
    removeToken()
  },
  setUserInfo(state, data) {
    state.userInfo = data
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  async login(store, data) {
    const res = await login(data)
    // console.log(res);
    store.commit('setToken', res)
    localStorage.setItem('loginTime', Date.now())
  },
  async getUserInfo(store) {
    const res = await getUserInfo()
    const data = await getUserDetailById(res.userId)
    // console.log(res);
    store.commit('setUserInfo', { ...res, ...data })
  },
  logout(store) {
    store.commit('removeToken')
    store.commit('removeUserInfo')
    resetRouter()
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}

